package com.bawei.module_home.viewmodel

import androidx.lifecycle.viewModelScope
import com.bawei.library_mvi.model.BaseViewModel
import com.bawei.module_home.intent.CommentIntent
import com.bawei.module_home.model.service.CommentService
import com.bawei.module_home.state.CommentState
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * @Author : yaotianxue
 * @Time : On 2023/7/6 16:28
 * @Description : CommentViewModel
 */
class CommentViewModel:BaseViewModel<CommentIntent>() {
    private val service:CommentService by lazy{CommentService()}
    private val _state = MutableStateFlow<CommentState>(CommentState.Init)
    val state: StateFlow<CommentState>
        get() = _state




    //处理意图
    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when(it){
                    is CommentIntent.GetCommentInfo -> doGetComment(it)//获得评论
                    is CommentIntent.PublishComment -> doPublishComment(it)//发布评论
                }
            }
        }
    }

    private fun doGetComment(it: CommentIntent.GetCommentInfo) {
        viewModelScope.launch {
            flow{
                val comments = service.getComments(it.datatype, it.itemid)
                emit(comments)

            }.catch { exeception->  _state.value = CommentState.CommentFailedState}
                .collect{
                    if(it.code == 0 && it.data != null && it.data.size > 0){
                        _state.value = CommentState.CommentSuccessState(it.data)
                    }
                }
        }
    }
    //发布评论
    private fun doPublishComment(it: CommentIntent.PublishComment) {
        viewModelScope.launch {
            flow {
                val comments = service.publishComment(it.entity)
                emit(comments)
            }.catch { exeception ->
                if (exeception.message?.contains("401") == true) {
                    _state.value = CommentState.PublishComment401Failed
                } else {
                    _state.value = CommentState.PublishCommentFailed
                }
            }.collect {
                if (it.code == 0 && it.data != null) {
                    _state.value = CommentState.PublishCommentSuccess(it.data)
                }
            }
        }
    }


}